package android.medicalcloud.com.yiapp.yilian.utils.android;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.StringTools;
import android.medicalcloud.com.yiapp.yilian.application.YilianAppcation;
import android.medicalcloud.com.yiapp.yilian.configer.xml.UrlRes;
import android.medicalcloud.com.yiapp.yilian.utils.glide.MyBitmapImageViewTarget;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 图片缓存类
 *
 * @author linxi
 *         异步加载图片
 */
public class ImageLoader {


    Context context;

    int stub_id;
    static ImageLoader instance;

    public static ImageLoader getInstance(Context context, int iconDefaultResId) {
        if (instance == null) {
            return new ImageLoader(context, iconDefaultResId);
        }
        return instance;
    }

    public static ImageLoader getInstance(Context context) {
        if (instance == null) {
            return new ImageLoader(context, 0);
        }
        return instance;
    }

    public ImageLoader(Context context) {
        this(context, 0);
    }

    public ImageLoader(Context context, int iconDefaultResId) {
        // 默认图片
        this.context = context;
        stub_id = iconDefaultResId;


    }

    public void displayImage(String url, ImageView imageView) {
        if (StringTools.isNullOrEmpty(url))
            return;
        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_CROP));


    }

    public void displayImageCenterInside(String url, ImageView imageView) {
        if (StringTools.isNullOrEmpty(url))
            return;
        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_INSIDE));


    }


    public void displayImage1(String url, BitmapImageViewTarget target) {
        if (StringTools.isNullOrEmpty(url))
            return;
//        Glide.with(context)
//                .load(getUrl(url))
//                .asBitmap()
//                .placeholder(stub_id)
//                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_CROP));

        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(stub_id)
                .into(target);

    }

    public void displayLocalImage(String url, ImageView imageView) {
        if (StringTools.isNullOrEmpty(url))
            return;
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.FIT_XY));

    }

    public void displayLocalImageCenterInside(String url, ImageView imageView) {
        if (StringTools.isNullOrEmpty(url))
            return;
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_INSIDE));

    }

    private String getUrl(String uri) {
        if (uri.startsWith("http")) {
            return uri;
        }
//       Logger.e("---image-"+UrlRes.getInstance().getImageUrl() + uri);
        return UrlRes.getInstance().getImageUrl() + uri;
    }

    public void displayHtmlImage(String url, ImageView imageView) {
        if (StringTools.isNullOrEmpty(url))
            return;
        Glide.with(context)
                .load(url)
                .centerCrop()
                .placeholder(stub_id)
                .into(imageView);

    }

    public void loadLocalImage(String path, ImageView imageView) {

        if (TextUtils.isEmpty(path)
                || null == imageView) {
            return;
        }

        Glide.with(context)
                .load(path)
                .centerCrop()
                .placeholder(R.drawable.default_image)
                .into(imageView);
    }

    public void loadimageTophoneOUt(String path) {
        Logger.e("-loadimageTophoneOUt-");
        new MyThread(path).start();
    }

    public void saveImage(String path) {
        Logger.e("-loadimageTophoneOUt-");
        new MyThread(path).start();
    }


    public void loadimageTophone(String path) {
        try {
            Bitmap bitmap = Glide.with(context)
                    .load(getUrl(path))
                    .asBitmap()
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();

            Logger.e(bitmap.getHeight() + "----------------------------");
            saveImageToGallery(YilianAppcation.instance.getApplicationContext(), bitmap);

//            if (Build.VERSION.SDK_INT <24){
//                saveImageToGallery(YiApplication.getInstance().getApplicationContext(),bitmap);
//
//            }else {            saveImageToGallery7(YiApplication.getInstance().getApplicationContext(),bitmap);
//            }
        } catch (Exception e) {
            Logger.e(e.getLocalizedMessage(), e);
        }

    }

    private class MyThread extends Thread {
        String path;

        public MyThread(String path) {
            this.path = path;
        }

        @Override
        public void run() {
            super.run();
            loadimageTophone(path);
        }
    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName = "yyFile";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    currentFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }

    public void saveImageToGallery7(Context context, Bitmap bmp) {
        // 首先保存图片
//        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName = "yyFile";
        File appDir = new File(Environment.getExternalStorageDirectory(), fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    currentFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

    }


}


